import requests
from sqlalchemy import create_engine
from sqlalchemy.orm import sessionmaker

from entity import ThsConvertibleBondInfo

ths_url = 'http://data.10jqka.com.cn/ipo/kzz/'
headers = {
    "Accept": "application/json, text/javascript, */*; q=0.01",
    "Dnt": "1",
    "Hexin-V": "A44l_EyPZjCT3tIU_XchdGWh329VD1IJZNMG7bjX-hFMGyCRIJ-iGTRjVv6L",
    "Referer": "http://data.10jqka.com.cn/ipo/bond/",
    "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/115.0.0.0 Safari/537.36"
}
r = requests.get(url=ths_url, headers=headers)
r_json = r.json()

# 初始化数据库连接:
engine = create_engine('mysql+pymysql://root:luxu123456@139.224.254.55:3306/convertible_bond')
# 创建DBSession类型:
DBSession = sessionmaker(bind=engine)
# 创建session对象:
session = DBSession()

for item in r_json['list']:  # 按索引
    old_info = session.query(ThsConvertibleBondInfo).filter(
        ThsConvertibleBondInfo.bond_code == item['bond_code']).first()
    new_info = ThsConvertibleBondInfo(**item)
    if old_info is None:
        session.add(new_info)
    else:
        if old_info.isEquals(new_info):
            print(True)
        else:
            print(False)
    # 提交即保存到数据库:
    session.commit()
# 关闭session:
session.close()
